import React, { Component } from 'react';
import store from '../redux'
import styles from './scss/main.scss'

import Layout from 'antd/lib/layout';
import Tabs from 'antd/lib/tabs'
import Menu from 'antd/lib/menu'
import Icon from 'antd/lib/icon'

import Nav from '../Component/nav'

import Home from './home'


import CustomProductManage from './innerComponent/customManage/custom-product-manage'
import CustomRechargeManage from './innerComponent/customManage/custom-recharge-manage'
import CustomTemplateManage from './innerComponent/customManage/custom-template-manage'
import CustomSignManage from './innerComponent/customManage/custom-sign-manage'
import CustomRegistManage from './innerComponent/customManage/custom-regist-manage'

import ProductInformation from './innerComponent/productManage/product-information'

import ChannelInformation from './innerComponent/channelManage/channel-information'
import ChannelSign from './innerComponent/channelManage/channel-sign'
import ChannelTemplate from './innerComponent/channelManage/channel-template'
import ChannelRecharge from './innerComponent/channelManage/channel-recharge'

import AccountBlacklist from './innerComponent/filterManage/account-blacklist'
import PlatformBlacklist from './innerComponent/filterManage/platform-blacklist'
import SensitiveWord from './innerComponent/filterManage/sensitive-word'
import WhiteList from './innerComponent/filterManage/whiteList'

import MarketSend from './innerComponent/sendManage/market-send'

import BatchList from './innerComponent/messageManage/batch-list'
import SendList from './innerComponent/messageManage/send-list'
import UpList from './innerComponent/messageManage/up-list'
import ApproveList from './innerComponent/messageManage/approve-list'

import ChannelDaySendStatistics from './innerComponent/statisticsManage/channel-day-send-statistics'
import ChannelMonthSendStatistics from './innerComponent/statisticsManage/channel-month-send-statistics'
import CustomDaySendStatistics from './innerComponent/statisticsManage/custom-day-send-statistics'
import CustomMonthSendStatistics from './innerComponent/statisticsManage/custom-month-send-statistics'
import SystemDaySendStatistics from './innerComponent/statisticsManage/system-day-send-statistics'
import SystemMonthSendStatistics from './innerComponent/statisticsManage/system-month-send-statistics'

import AdminList from './innerComponent/systemManage/admin-list'
import RoleManage from './innerComponent/systemManage/role-manage'
import AthorityManage from './innerComponent/systemManage/athority-manage'
import ControlCenter from './innerComponent/systemManage/control-center'
import LogBook from './innerComponent/systemManage/logbook'
import SendMsg from './innerComponent/systemManage/send-message'

import CustomAcountManage from'./innerComponent/customManage/custom-account-manage'


const NavToCom = {
    '/main/home':<Home/>,
    "/main/custom-account":<CustomAcountManage />,
    "/main/custom-product":<CustomProductManage/>,
    "/main/custom-recharge":<CustomRechargeManage/>,
    "/main/custom-template":<CustomTemplateManage/>,
    "/main/custom-regist":<CustomRegistManage/>,
    "/main/custom-sign":<CustomSignManage />,
    "/main/product-information":<ProductInformation/>,
    "/main/channel-information":<ChannelInformation/>,
    "/main/channel-sign":<ChannelSign/>,
    "/main/channel-template":<ChannelTemplate/>,
    "/main/channel-recharge":<ChannelRecharge/>,
    "/main/market-send":<MarketSend/>,                
    "/main/sensitive-word":<SensitiveWord/>,
    "/main/platform-blacklist":<PlatformBlacklist/>,
    "/main/account-blacklist":<AccountBlacklist/>,
    "/main/white-list":<WhiteList />,
    "/main/batch-list":<BatchList/>,
    "/main/send-list":<SendList/>,
    "/main/up-list":<UpList/>,
    "/main/approve-list":<ApproveList/>,
    "/main/custom-day-send-statistics":<CustomDaySendStatistics/>,
    "/main/custom-month-send-statstics":<CustomMonthSendStatistics/>,
    "/main/channel-day-send-statistics":<ChannelDaySendStatistics/>,
    "/main/channel-month-send-statistics":<ChannelMonthSendStatistics/>,
    "/main/system-day-send-statistics":<SystemDaySendStatistics/>,
    "/main/system-month-send-statistics":<SystemMonthSendStatistics/>,
    "/main/admin-list":<AdminList/>,
    "/main/role-manage":<RoleManage/>,
    "/main/athority-manage":<AthorityManage/>,
    "/main/control-center":<ControlCenter/>,
    "/main/logbook":<LogBook/>,
    "/main/send-message":<SendMsg/>     
}

const { Header, Footer, Sider, Content} = Layout;


const SubMenu = Menu.SubMenu;
const TabPane = Tabs.TabPane;

const nameToNav = {};
const NavToName = {};
const nameToNavArr = [];

class Main extends Component {
    constructor(props) {
        super(props)
        this.state = {
            windowHeight: 200,
            layoutLeft: 205,
            contentHeight: 0,
            nowNav: ['home'],
            defaultOpenKeys: [],
            openKeys: [],
            sideCollapse: false,
            navs: null,
            tabNavs:[],
            activeTab:'',
            tabUrls:[]
        }
    }
    componentDidMount() {
        const navPath = JSON.parse(localStorage.getItem('menu'));
        if (navPath.length === 0) {
            document.location.pathname = '/noAuth'
        } else {
            let navs = navPath.map((item, index) => {
                return this.circleNav(item)
            })
            this.setState({
                navs
            }, () => {
                this.defaultNav()
                const path = document.location.pathname;
                let pathName = '';
                for(let key in nameToNav){
                    if(nameToNav[key] === path){
                        pathName = key
                    }
                }
                this.setState({
                    tabUrls:[path],
                    tabNavs:[{name:pathName,com:NavToCom[path]}],
                    activeTab:pathName
                })
                this.fullContent()
                window.addEventListener('resize', () => { this.fullContent() })
            })

            let siderTrigger = document.getElementsByClassName('ant-layout-sider-trigger');
            siderTrigger[0].style.width = '210px';
            siderTrigger[0].style.height = '40px';
        }
    }
    //遍历路径树，构造左边导航树
    circleNav(data) {
        let getItem = (data) => {
            if (data.children.length !== 0 && data.type !== 'BUTTON') {
                if (data.children[0].type !== 'BUTTON') {
                    let arr = [];
                    data.children.forEach((item, index) => {
                        arr.push(getItem(item))
                    })
                    return (
                        <SubMenu key={data.code} title={<span><Icon type={data.icon} /><span>{data.name}</span></span>}>
                            {arr}
                        </SubMenu>)
                }
                else {
                    if (data.type !== 'BUTTON') {
                        NavToName['/main/'+data.path] = data.name;
                        nameToNav[data.name] = '/main/'+data.path;
                        nameToNavArr.push(data);
                        return (
                            <Menu.Item key={data.path ? data.path : data.name}>
                                <Icon type={data.icon} />
                                <span>{data.name}</span>
                            </Menu.Item>
                        )
                    }
                }
            }
        }
        return getItem(data)
    }
    //获取默认路径
    defaultNav() {
        const navPath = JSON.parse(localStorage.getItem('menu'));
        let pathname = document.location.pathname;
        if(pathname === '/main'){
            pathname = '/main/'+nameToNavArr[0].path;
            document.location.pathname = pathname;
        }
        const arr = pathname.split('/');
        let path = arr[arr.length - 1];
        let pathArr = [path];
        let openKeys = [];

        let cirKeys = (arr) => {
            arr.forEach((item) => {
                if (item.path === path) {
                    openKeys.push(item.parent);
                    path = item.parent;
                    cirKeys(navPath);
                }
                else {
                    if (item.children.length) {
                        cirKeys(item.children);
                    }
                }
            })
        }
        cirKeys(navPath);
        this.setState({
            nowNav: pathArr,
            defaultOpenKeys: openKeys
        })
    }
    //计算内容区高度
    fullContent() {
        let height = document.documentElement.clientHeight;
        this.setState({
            contentHeight: height - 65 - 40
        }, () => {
            this.mainContent.style.height = this.state.contentHeight + 'px';
            store.dispatch({ type: 'Height', value: this.state.contentHeight })
        })
    }
    changePage(param) {
        let pathname = param.key;
        let path = "/main/" + pathname;
        const arr = JSON.parse(JSON.stringify(this.state.tabUrls));
        const pathName = NavToName[path];
        let navs = [];
        if(arr.indexOf(path)<0){
            arr.push(path)
        }
        arr.forEach((item)=>{
            navs.push({name:NavToName[item],com:NavToCom[item]})
        })
        this.setState({
            tabUrls:arr,
            tabNavs:navs,
            activeTab:pathName
        })
        this.props.history.replace(path);
        this.defaultNav();
        this.fullContent();        
    }
    handleOpenChange(keys) {
        this.setState({
            openKeys: keys,
            defaultOpenKeys: keys
        })
    }
    collapseChange(collapsed) {
        this.setState({
            layoutLeft: collapsed ? this.sider.props.collapsedWidth - 1 : this.sider.props.width - 1
        }, () => {
            let siderTrigger = document.getElementsByClassName('ant-layout-sider-trigger');
            siderTrigger[0].style.width = this.state.layoutLeft + 'px';
        })
        if (collapsed) {
            this.setState({
                defaultOpenKeys: []
            })
        }
        else {
            this.defaultNav()
        }
    }
    toggleCollapsed() {
        this.setState({
            sideCollapse: !this.state.sideCollapse
        })
        this.collapseChange(!this.sider.props.collapsed);
    }
    changeTab(tab){
        this.props.history.replace(nameToNav[tab]);
        this.setState({
            activeTab:tab
        })
        this.defaultNav();
        this.fullContent()        
    }
    editTab(param){
        let navs=[];
        const path = nameToNav[param];
        const arr = JSON.parse(JSON.stringify(this.state.tabUrls));
        arr.splice(arr.indexOf(path),1);
        const active= this.state.activeTab !== param ? this.state.activeTab : NavToName[arr[arr.length-1]];
        arr.forEach((item)=>{
            navs.push({name:NavToName[item],com:NavToCom[item]})
        })
        this.changeTab(active);
        this.setState({
            tabUrls:arr,
            tabNavs:navs,
            activeTab:active
        })
    }
    render() {
        return (
            <Layout className={styles['box']}>
                <Header className={styles.header}>
                    <Nav history={this.props.history} toggleCollapsed={this.toggleCollapsed.bind(this)} isCollapsed={this.state.sideCollapse}></Nav>
                </Header>
                <Layout style={{ marginLeft: this.state.layoutLeft, height: this.state.contentHeight + 'px' }}>
                    <Sider className={styles.sider} style={{ height: this.state.contentHeight + 'px' }} width='210' collapsed={this.state.sideCollapse} collapsible={true} onCollapse={this.toggleCollapsed.bind(this)} ref={(box) => { this.sider = box }}>
                        <Menu theme="dark" mode="inline" openKeys={this.state.defaultOpenKeys}  selectedKeys={this.state.nowNav} onSelect={this.changePage.bind(this)} onOpenChange={this.handleOpenChange.bind(this)}>
                            {this.state.navs}
                        </Menu>
                    </Sider>
                    <div className={styles['main-content']} ref={(item) => { this.mainContent = item }}>
                        <Content>
                            <Tabs style={{height:this.state.contentHeight + 'px'}} hideAdd activeKey={this.state.activeTab} onEdit={this.editTab.bind(this)} onChange={this.changeTab.bind(this)} type="editable-card">
                                {this.state.tabNavs.map(item=><TabPane tab={item.name} key={item.name} closable={this.state.tabNavs.length !== 1}>{item.com}</TabPane>)}
                            </Tabs>
                        </Content>
                    </div>
                </Layout>
                <Footer className={styles.footer}>
                    Copyright © 上海展奎科技有限公司
                </Footer>
            </Layout>
        )
    }
}

export default Main